<template>
  <div>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="表单名" prop="formName">
        <el-input v-model="formData.formName" placeholder="请输入表单名" />
      </el-form-item>
      <el-form-item label="表单Key" prop="formKey">
        <el-input v-model="formData.formKey" placeholder="请输入表单Key" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :value="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" type="textarea" />
      </el-form-item>
    </el-form>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="close" >取 消</el-button>
  </div>
</template>


<script lang="ts" setup>
import * as FormApi from '@/api/bpm/form'
import {DICT_TYPE, getIntDictOptions} from "@/utils/dict";
import {CommonStatusEnum} from "@/utils/constants";
import {integer} from "vue-types";

defineOptions({name: 'AmisFormEditor'})

console.log('AmisFormEditor....')

const { t } = useI18n() // 国际化
const message = useMessage() // 消息

const formLoading = ref(false) // 表单的加载中：提交的按钮禁用
const formData = ref({
  formName: '',
  formKey: '',
  status: CommonStatusEnum.ENABLE,
  remark: '',
  formType:15
})

const formRules = reactive({
  formName: [{ required: true, message: '表单名不能为空', trigger: 'blur' }],
  formKey: [{ required: true, message: '表单Key不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '开启状态不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const props = defineProps({
  editFormId: {
    type: integer,
    required: true,
  },
  closeEditForm: {
    type: Function,
    required: true,
  }
})


/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as FormApi.FormVO
    if (!data.id) {
      await FormApi.createForm(data)
      message.success(t('common.createSuccess'))
    } else {
      await FormApi.updateForm(data)
      message.success(t('common.updateSuccess'))
    }
    close()
  } finally {
    formLoading.value = false
  }
}
/** 关闭按钮 */
const close = () => {
  props.closeEditForm();
}

/** 初始化 **/
onMounted(async () => {
  // 场景一：新增表单
  const editFormId = props.editFormId as unknown as number
  if (!editFormId) {
    return
  }
  // 场景二：修改表单
  const data = await FormApi.getForm(editFormId)
  formData.value = data
})

</script>
